<?php

namespace common\models\datas;

use common\components\extenders\MenuManage;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%packet}}".
 *
 * @property integer $id
 * @property string $name
 * @property string $description
 * @property integer $status
 * @property integer $start_time
 * @property integer $end_time
 * @property integer $amount
 * @property integer $number
 * @property integer $created_at
 * @property integer $updated_at
 */
class Packet extends \common\components\bases\BaseModel
{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%packet}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['status', 'amount', 'number', 'created_at', 'updated_at','packet_min_proportion','packet_max_proportion'], 'integer'],
            [['name','amount','start_time','end_time','number','packet_1','packet_2','packet_3','packet_4','packet_5','packet_min_proportion','packet_max_proportion'],'required'],
            [['name','packet_1','packet_2','packet_3','packet_4','packet_5'], 'string', 'max' => 100],
            [['description'], 'string', 'max' => 255],
            [['packet_min_proportion','packet_max_proportion'], 'compare', 'compareValue' =>100, 'operator' => '<'],
            [['packet_max_proportion'], 'check_proportion'],
            [['packet_1'], 'min_validate'],
            [['packet_5'], 'max_validate'],
            [['packet_1','packet_2','packet_3','packet_4'], 'order_validate'],
            [['packet_max_proportion'], 'avg_validate'],
            [['end_time'], 'time_validate'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('common', '自增id'),
            'name' => Yii::t('common', '名称'),
            'description' => Yii::t('common', '描述'),
            'status' => Yii::t('common', '是否暂停'),
            'start_time' => Yii::t('common', '开始时间'),
            'end_time' => Yii::t('common', '结束时间'),
            'amount' => Yii::t('common', '总金额'),
            'number' => Yii::t('common', '总数量'),
            'created_at' => Yii::t('common', '创建时间'),
            'updated_at' => Yii::t('common', '修改时间'),
            'packet_1' => Yii::t('common', '最小金额'),
            'packet_2' => Yii::t('common', '金额'),
            'packet_3' => Yii::t('common', '金额'),
            'packet_4' => Yii::t('common', '金额'),
            'packet_5' => Yii::t('common', '最大金额'),
            'packet_min_proportion' => Yii::t('common', '最小金额比例'),
            'packet_max_proportion' => Yii::t('common', '最大金额比例'),
        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['created_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };
        $fields['status'] = function () {
            switch ($this->status) {
                case 1:
                    return \Yii::t('common', '开启');
                case 2:
                    return \Yii::t('common', '结束');
                case 3:
                    return \Yii::t('common', '暂停');
                case 0:
                    return \Yii::t('common', '未开始');
            }
        };
        $fields['updated_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->updated_at);
        };
        $fields['start_time'] = function () {
            return \Yii::$app->formatter->asDatetime($this->start_time);
        };
        $fields['end_time'] = function () {
            return \Yii::$app->formatter->asDatetime($this->end_time);
        };
        return $fields;
    }

    public function extraFields()
    {
        return [
            'num' => function(){
                return isset($this->receiveNum)? count($this->receiveNum):0;
            },

            'operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    ['update' => function ($data) {
                            if ($data['end_time']<=time()) {//结束之后不能修改
                                return '<span style="color:#ccc">修改</span>';
                            } else {
                                return '';
                            }
                        },
                        'delete' => function ($data) {//开始之后不能删除
                            if ($data['start_time']<=time()) {
                                return '<span style="color:#ccc">删除</span>';
                            } else {
                                return '';
                            }
                        },
                    ]
                )->create();
            },
        ];
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ],
        ]);
    }
    public function check_proportion($attribute){
        if ($this->packet_min_proportion +$this->packet_max_proportion>=100) {
            $this->addError($attribute, Yii::t('common', '比例之和必须小于100！'));
            $this->addError('packet_min_proportion', Yii::t('common', '比例之和必须小于100！'));
        }
    }

    public function min_validate($attribute){
        $avg=$this->amount/$this->number;
        if ($this->packet_1>=$avg) {
            $this->addError($attribute, Yii::t('common', '最小金额应小于平均值{avg}！',['avg'=>$avg]));
        }
    }

    public function max_validate($attribute){
        $avg=$this->amount/$this->number;
        if ($this->packet_5<=$avg) {
            $this->addError($attribute, Yii::t('common', '最大金额应大于平均值{avg}！',['avg'=>$avg]));
        }
    }

    public function order_validate($attribute)
    {
        $array1 = ['packet_1' => '', 'packet_2' => '', 'packet_3' => '', 'packet_4' => '', 'packet_5' => ''];
        $array2 = ['packet_1' => '', 'packet_2' => '', 'packet_3' => '', 'packet_4' => '', 'packet_5' => ''];
        foreach ($array1 as $k => $v) {
            if (!empty($this->$k) && strpos($this->$k, '-')) {//区间
                $array = explode('-', $this->$k);
                $array1[$k] = $array[0];
                $array2[$k] = $array[1];
            }
            if (!empty($this->$k) && (!strpos($this->$k, '-'))) {//区间
                $array1[$k] = $this->$k;
                $array2[$k] = $this->$k;
            }
        }
            $array_1 = array_values($array1);
            foreach ($array_1 as $key => $val) {
                if ($array_1[$key] != '') {
                    for ($i = $key + 1; $i <5; $i++) {
                        if ($array_1[$i] != '' && $array_1[$key] >= $array_1[$i]) {
                            $num = $key + 1;
                            $this->addError('packet_' . $num, Yii::t('common', '金额应升序排列！'));
                        }
                    }
                }
            }
            $array_2 = array_values($array2);
            foreach ($array_2 as $key => $val) {
                if ($array_2[$key] != '') {
                    for ($i = $key + 1; $i <5; $i++) {
                        if ($array_2[$i] != '' && $array_2[$key] >= $array_2[$i]) {
                            $num = $key + 1;
                            $this->addError('packet_' . $num, Yii::t('common', '金额应升序排列！'));
                        }
                    }
                }
            }
        }

    public function avg_validate($attribute){
        if(!empty($this->packet_5) && !empty($this->packet_1)  && !empty($this->packet_max_proportion)  && !empty($this->packet_min_proportion)){
            $total=($this->packet_5*$this->packet_max_proportion+$this->packet_1*$this->packet_min_proportion)*$this->number/100;
            if($total>=$this->amount){
                $this->addError($attribute, Yii::t('common', '最大最小金额之和为{total},超出总金额！',['total'=>$total]));
            }else{
                if(!empty($this->packet_2) && !empty($this->packet_3) && !empty($this->packet_4)){
                    $number=($this->packet_max_proportion+$this->packet_min_proportion)*$this->number/100;
                    $avg=($this->amount-$total)/($this->number-$number);
                    if(!(strpos($this->packet_2, '-')) && $avg<$this->packet_2){
                        $this->addError($attribute, Yii::t('common', '剩余金额与数量的平均值为{avg}，应该大于“金额1”！',['avg'=>$avg]));
                    }
                    if((strpos($this->packet_2, '-'))){
                        $array = explode('-', $this->packet_2);
                        if($array[0]>$avg){
                            $this->addError($attribute, Yii::t('common', '剩余金额与数量的平均值为{avg}，应该大于“金额1”的区间最小值！',['avg'=>$avg]));
                        }
                    }
                    if($avg>$this->packet_4){
                        $this->addError($attribute, Yii::t('common', '剩余金额与数量的平均值为{avg}，应该小于“金额3”',['avg'=>$avg]));
                    }
                    if((strpos($this->packet_4, '-'))){
                        $array = explode('-', $this->packet_4);
                        if($array[1]<$avg){
                            $this->addError($attribute, Yii::t('common', '剩余金额与数量的平均值为{avg}，应该小于“金额3”的区间最大值！',['avg'=>$avg]));
                        }
                    }
                }

            }
        }
    }

    public function time_validate($attribute){
        if(!empty($this->start_time)){
            $start_time=strtotime($this->start_time);
            $end_time=strtotime($this->end_time);
            if($start_time>=$end_time){
                $this->addError($attribute, Yii::t('common', '结束时间应该大于开始时间！'));
            }
        }
    }

    public function getReceiveNum(){
        return $this->hasMany(PacketAttr::className(),['packet_id'=>'id'])->where(['status'=>1]);
    }
}
